<template>
  <div>
    <el-card>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="sortDate"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tags -->
      <el-tabs v-model="activeName" @tab-click="handleTagsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="dialogParamsAdd = true"
            >添加参数<i class="el-icon-circle-plus-outline el-icon--right"></i
          ></el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
              <!-- 下拉显示的tag标签 -->
            <el-table-column type="expand" width="60">
              <template slot-scope="scope">
                <el-tag
                  class="eltag"
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="60">
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="warning"
                  icon="el-icon-edit"
                  size="small"
                  @click="showParamsEdit(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeParamstEdit(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="dialogParamsAdd = true"
            >添加属性<i class="el-icon-circle-plus-outline el-icon--right"></i
          ></el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
              <!-- 下拉显示的tag标签 -->
             <el-table-column type="expand" width="60">
              <template slot-scope="scope">
                <el-tag
                  class="eltag"
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="60">
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="warning"
                  icon="el-icon-edit"
                  size="small"
                  @click="showParamsEdit(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeParamstEdit(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数弹出框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="dialogParamsAdd"
        width="60%"
        @close="addParamsClosed"
      >
        <el-form
          :model="addParamsData"
          :rules="addFromRules"
          ref="addFromRef"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamsData.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addParams">确 定</el-button>
          <el-button @click="dialogParamsAdd = false">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数弹出框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="dialogParamsEdit"
        width="60%"
      >
        <el-form
          :model="editParamsData"
          :rules="editFromRules"
          ref="editFromRef"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParamsData.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editParams">确 定</el-button>
          <el-button @click="dialogParamsEdit = false">取 消</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  //import 引入组件
  components: {},
  data() {
    return {
      //商品分类列表
      sortDate: [],
      //级联双向绑定的数组
      selectCateKeys: [],
      //被激活的tags名称
      activeName: "many",
      //动态属性数据
      manyTableData: [],
      //静态属性数据
      onlyTableData: [],
      //添加参数的表单数据
      addParamsData: {
        attr_name: "",
      },
      dialogParamsAdd: false,
      //添加参数表单验证规则
      addFromRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      dialogParamsEdit: false,
      //添加参数表单验证规则
      editFromRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      //修改参数的表单数据
      editParamsData: {},
    };
  },
  methods: {
    //获取商品分类列表
    async getCategories() {
      const { data } = await this.$axios.get("/categories", {
        type: [1, 2, 3],
      });
      // console.log(data);
      if (data.meta.status == 200) {
        this.sortDate = data.data;
      }
    },
    //获取参数的列表数据
    async getParamsData() {
      //选中的不是三级分类时
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[];
        return;
      }
      //选中的是三级分类时
      // console.log(this.selectCateKeys);
      //根据所选分类的id，和当前所处面板，获取对应参数
      const { data } = await this.$axios.get(
        `/categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }

      data.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框跟按钮显示
        (item.inputVisible = false),
          // 添加tag文本框输入的内容
          (item.inputValue = "");
      });
      // console.log(data.data);
      if (this.activeName == "many") {
        this.manyTableData = data.data;
      } else {
        this.onlyTableData = data.data;
      }
    },
    //级联选择框选项变化触发
    handleChange() {
      this.getParamsData();
    },
    //tags切换触发
    handleTagsClick() {
      // console.log(this.activeName);
      this.getParamsData();
    },
    //确认添加参数
    addParams() {
      //表单验证
      this.$refs.addFromRef.validate(async (valid) => {
        //表单验证不对直接返回
        if (!valid) return;
        //表单验证成功开始请求
        const { data } = await this.$axios.post(
          `/categories/${this.cateId}/attributes`,
          { attr_name: this.addParamsData.attr_name, attr_sel: this.activeName }
        );
        console.log(data);
        if (data.meta.status !== 201) {
          return this.$message.error(data.meta.msg);
        }
        this.$message.success(data.meta.msg);
        this.dialogParamsAdd = false;
        this.getParamsData();
      });
    },
    //添加对话框关闭事件
    addParamsClosed() {
      this.$refs.addFromRef.resetFields();
    },
    //打开编辑对话框
    async showParamsEdit(id) {
      this.dialogParamsEdit = true;
      const { data } = await this.$axios.get(
        `/categories/${this.cateId}/attributes/${id}`
      );
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }
      this.editParamsData = data.data;
    },
    //确认修改参数
    editParams() {
      this.$refs.editFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data } = await this.$axios.put(
          `/categories/${this.cateId}/attributes/${this.editParamsData.attr_id}`,
          {
            attr_name: this.editParamsData.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (data.meta.status !== 200) {
          this.$message.error(data.meta.msg);
        }
        this.$message.success(data.meta.msg);
        this.dialogParamsEdit = false;
        this.getParamsData();
      });
    },
    //删除参数事件
    async removeParamstEdit(id) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该标签, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRes !== "confirm") {
        return this.$message.info("已取消");
      }
      // 确认删除
      const { data } = await this.$axios.delete(
        `/categories/${this.cateId}/attributes/${id}`
      );
      if (data.meta.status !== 200) {
        this.$message.error(data.meta.msg);
      }
      this.$message.success(data.meta.msg);
      this.getParamsData();
    },
    //文本框失去焦点或按下enter触发
    handleInputConfirm(info) {
      if (info.inputValue.trim().length === 0) {
        info.inputValue = "";
        info.inputVisible = false;
        return;
      }
      info.attr_vals.push(info.inputValue.trim());
      info.inputValue = '';
      info.inputVisible = false;
      // 添加到数据库
      this.saveAttrVals(info)
    },

    // 增加tag按钮点击事件
    showInput(info) {
      info.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //将attr_vals存入数据库的方法
    async  saveAttrVals(val){
      const { data } = await this.$axios.put(
        `/categories/${this.cateId}/attributes/${val.attr_id}`,
        {
          attr_name: val.attr_name,
          attr_sel: val.attr_sel,
          attr_vals: val.attr_vals.join(" "),
        }
      );
      if (data.meta.status !== 200) {
        this.$message.error(data.meta.msg);
      }
      this.$message.success(data.meta.msg);
    },
    //删除tag标签
    removeTag(i,info){
      info.attr_vals.splice(i,1)
      this.saveAttrVals(info)
    },
  },
  mounted() {
    this.getCategories();
  },
  computed: {
    //判断按钮是否要被禁用
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 选中的三级分类id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2];
      }
      return null;
    },
    //动态计算标题的文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style scoped>
.eltag {
  margin: 8px;
}
.input-new-tag {
  width: 150px;
}
</style>
